package main

import (
	"encoding/base64"
	"encoding/json"
	"log"
	"net/http"
	"time"
)

func main() {
	// UserInfo 定义用户信息结构体
	type UserInfo struct {
		Email     string `json:"email"`
		FirstName string `json:"first_name"`
		LastName  string `json:"last_name"`
		UserID    string `json:"user_id"`
		Username  string `json:"username"`
	}

	// 处理静态文件
	http.Handle("/", http.FileServer(http.Dir("log")))
	// 处理 /index 路径
	http.HandleFunc("/index", func(w http.ResponseWriter, r *http.Request) {
		// 获取 user_info 参数
		userInfoParam := r.URL.Query().Get("user_info")
		// 对 user_info 进行 Base64 解码
		decodedUserInfo, _ := base64.URLEncoding.DecodeString(userInfoParam)
		if userInfoParam != "" {
			// 解析 JSON 数据到 UserInfo 结构体
			var userInfo UserInfo
			err := json.Unmarshal(decodedUserInfo, &userInfo)
			if err != nil {
				http.Error(w, "Failed to parse user info", http.StatusBadRequest)
				return
			}

			// 提取 email 字段
			email := userInfo.Email
			cookie := &http.Cookie{
				Name:     "user_info",
				Value:    email,
				Path:     "/",
				HttpOnly: false, // 允许 JavaScript 访问
			}
			http.SetCookie(w, cookie)
		}
		http.Redirect(w, r, "/index.html", http.StatusFound)
	})

	// 处理退出登录路由
	http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		// 创建一个过期的 cookie 以删除原有的 cookie
		cookie := &http.Cookie{
			Name:     "user_info",
			Value:    "",
			Path:     "/",
			Expires:  time.Now().Add(-1 * time.Hour),
			HttpOnly: false,
		}
		http.SetCookie(w, cookie)
		// 重定向到登录页面或其他合适的页面
		http.Redirect(w, r, "/login.html", http.StatusFound)
	})
	// 启动服务器
	port := ":5000"
	log.Printf("服务器正在监听端口 %s...\n", port)
	if err := http.ListenAndServe(port, nil); err != nil {
		log.Fatalf("服务器启动失败: %v", err)
	}
}
